<template>
	<div class="h-full flex items-center">
    <!--<div class="flex-1 flex items-center pr-4">-->
      <!--<span class="text-sm mr-2 theme-front-color">区域选择</span>-->
      <!--<el-input placeholder="请选择区域信息"-->
                <!--style="width: 540px;"-->
                <!--class="filter-item"-->
                <!--size="mini"-->
                <!--:suffix-icon="showTree?'el-icon-arrow-up':'el-icon-arrow-down'"-->
                <!--@click.native="deptogglePanel($event)"-->
                <!--v-model="currentbuildInfo.buildingName">-->
      <!--</el-input>-->
      <!--<div v-show="showTree" class="objectTree1 w-1601" ref="suoShuMenTree">-->
        <!--<el-tree-->
          <!--:style="'height:'+containerHeight+'px'"-->
          <!--ref="buildTree"-->
          <!--highlight-current-->
          <!--node-key="buildingId"-->
          <!--:check-on-click-node="true"-->
          <!--:check-strictly="true"-->
          <!--show-checkbox-->
          <!--:data="dataList"-->
          <!--:expand-on-click-node="false"-->
          <!--:props="menuListTreeProps"-->
          <!--@check-change="selectBuild"-->
          <!--default-expand-all-->
        <!--&gt;</el-tree>-->
      <!--</div>-->

      <!--&lt;!&ndash;<el-cascader  v-model="currentbuildInfo" :options="buildings" :props="{ checkStrictly: true, value: 'buildingId', label: 'buildingName' }" size="small" class="flex-1"></el-cascader>&ndash;&gt;-->
    <!--&lt;!&ndash;&ndash;&gt;-->
    <!--</div>-->
		<el-button type="warning" size="small" @click="onToggleMinimap()">缩略图</el-button>
		<el-button type="primary" size="small" @click="handle_save()">保存</el-button>
		<!--<el-button type="success" size="small" @click="outputJson()">导出json</el-button>-->

  <el-dialog
    title="请输入文件名称"
    :visible.sync="dialogVisible"
    width="30%"
    :before-close="handleClose">
    <el-input v-model="name"></el-input>
    <span slot="footer" class="dialog-footer">
         <el-button @click="dialogVisible = false">取 消</el-button>
         <el-button type="primary" @click="handle_update">确 定</el-button>
        </span>
  </el-dialog>
  </div>
</template>

<script>
  import * as Util from "@/utils";
  import util from '@/libs/util'
  import list2tree from 'list2tree'

	export default {
		data() {
			return {
        name:"",
        dialogVisible:false,
        ztypevalue:"",
        bgurl:"",
        id:"",
        menuListTreeProps: {
          label: "buildingName",
          children: "children"
        },
        dataList: [],
        showTree:false,
        currentbuildInfo: {
          buildingName:'',
        },
				isMinimapActive: false,
        buildings: [],
        currentbuildInfo:[64,65]
			}
		},
    created() {
      this.getBuildings()
    },
    computed: {
      containerHeight() {
        return Util.getClientHeight() - 143;
      },
      bottomChartHeight(){
        return Util.getClientHeight() - 340;
      },
      event() {
        return this.$store.state.event.event
      }
    },
		methods: {
      handleClose(){
        this.dialogVisible = false
      },
      async open() {
        window.topology.open({"pens":[]});
        this.mycomponents = [];

        let idval = this.$route.query.id
        if (typeof(idval) != "undefined"){
          this.$api.okhttp({
            url: this.$http.adornUrl("/topologies/find"),
            method: "get",
            params: this.$http.adornParams({
              id: idval,
              customerId: this.$util.cookies.get("customer_id")
            })
          }).then((data) => {
            if (data && data.code === 0 && data.obj) {
              this.bgurl = data.obj.bgurl
              this.id = data.obj.id
              this.name = data.obj.name
              this.data = data.obj.data
              window.topology.open(JSON.parse(data.obj.data))
            }
            else{
            }
          });
        }
      },
      open_new() {
        window.topology.open({"pens":[]});
        let idval = this.currentbuildInfo.buildingId
        if (typeof(idval) != "undefined"){
          this.$api.okhttp({
            url: this.$http.adornUrl("/topologies/findbybuildId"),
            method: "get",
            params: this.$http.adornParams({
              id: idval,
              customerId: this.$util.cookies.get("customer_id")
            })
          }).then((data) => {
            if (data && data.code === 0 && data.obj) {
              window.topology.open(JSON.parse(data.obj.data))
            }
            else{
            }
          });
        }
      },

      selectBuild (data, checked, indeterminate) {
        if(checked){
          this.$refs.buildTree.setCheckedNodes([]);
          this.currentbuildInfo = data;
          this.$refs.buildTree.setChecked(data.buildingId,checked);
          this.showTree = false
          this.open();
        }
      },
      deptogglePanel (event) {
        event || (event = window.event)
        event.stopPropagation
          ? event.stopPropagation()
          : (event.cancelBubble = true)
        this.showTree ? this.dephide() : this.depshow()
      },
      depshow () {
        this.showTree = true;
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephide () {
        this.showTree = false
        document.addEventListener('click', this.dephidePanel, false)
      },
      dephidePanel (e) {
        if (
          this.$refs.suoShuMenTree &&
          !this.$refs.suoShuMenTree.contains(e.target)
        ) {
          this.dephide()
        }
      },

      async getBuildings() {
        let user = util.cookies.get('user')
        user = JSON.parse(user)
        // console.log(user)
        let project = util.cookies.get('project')
        project = JSON.parse(project)
        const data = await this.$api.getBuildings({
          page: 1,
          limit: 100000,
          customerId: user.customer_id,
          projectid: project.projectId,
          t: Date.now()
        })
        // console.log(res)
        // const getTreeData = list2tree({
        //   idKey: 'buildingId',
        //   parentIdKey: 'parentBuildingId'
        // })
        // const buildings = getTreeData(res.menuList)
        // // console.log(buildings)
        // this.buildings = buildings

        if (data && data.code === 0) {

          this.dataList = Util.treeDataTranslate(
            data.menuList,
            "buildingId",
            "parentBuildingId"
          );
          if(this.search){
            this.currentbuildInfo = (data.menuList&&data.menuList.length>0)?data.menuList.find(item=>item.parentBuildingId==-1):{};
            this.selectBuild(this.currentbuildInfo,true);
          }
          else{
            this.currentbuildInfo = (data.menuList&&data.menuList.length>0)?data.menuList.find(item=>item.parentBuildingId==-1):{};
          }
          this.$nextTick(() => {
             this.open();
          })
        } else {
          this.dataList = [];
        }

      },
			onToggleMinimap() {
				this.isMinimapActive = !this.isMinimapActive
				window.topology[this.isMinimapActive ? 'showMap' : 'hideMap']()
			},
			outputJson() {
				const filename = Date.now() + '.json'
				const data = window.topology.data()
				const json = JSON.stringify(data, undefined, 4)
				const blob = new Blob([json], { type: 'text/json' })
				const a = document.createElement('a')
				a.download = filename
				a.href = window.URL.createObjectURL(blob)
				a.dataset.downloadurl = ['text/json', a.download, a.href].join(':')
				a.click()
			},
      handle_save(data) {
        if(this.id===''){
          this.dialogVisible = true
          return ;
        }
        let req = '';
        const canvasdata = window.topology.data()
        req = JSON.stringify(canvasdata);
        this.$api.okhttp({
          url: this.$http.adornUrl("/topologies/update"),
          method: "post",
          data: this.$http.adornData({
            data: req,
            name:this.name,
            "id":this.id,
            customerId: this.$util.cookies.get("customer_id")
          })
        }).then((data) => {
          if (data && data.code === 0) {

            this.$router.push({ path: '/tempctl/zutai'})
          } else {
            this.$message.error("操作失败!");
          }
        });
      },
      handle_update(data) {
        let pens = [];
        let ztypevalue = '1';
        // for (var i in this.canvas.data.pens)
        // {
        //   pens.push(this.canvas.data.pens[i])
        // }
        let req = '';
        const canvasdata = window.topology.data()
        req = JSON.stringify(canvasdata);
        this.$api.okhttp({
          url: this.$http.adornUrl("/topologies/add"),
          method: "post",
          data: this.$http.adornData({
            data: req,
            name:this.name,
            bgurl:this.bgurl,
            customerId: this.$util.cookies.get("customer_id"),
            projectId: this.$util.cookies.get("cuuren_projectId")
          })
        }).then((data) => {
          if (data && data.code === 0) {

            this.dialogVisible = false;
            this.$router.push({ path: '/tempctl/zutai'})
            this.createcomponentflag = false;
            this.bgurl = '';
          } else {
            this.$message.error("操作失败!");
          }
        });
      },

      handle_save_new(data) {
        // console.log(this.currentbuildInfo)
        // if(this.currentbuildInfo && this.currentbuildInfo.buildingId ){
        //
        // }else{
        //   this.$message.error("请选择区域!");
        //   return false;
        // }
        const canvasdata = window.topology.data()
        console.log(1111,canvasdata)
        let imagesLen = canvasdata.pens.length;
        if(imagesLen==0){
          this.$message.error("请先绘制图形!");
          return false;
        }

        this.$api.okhttp({
          url: this.$http.adornUrl("/topologies/saveOrUpdate"),
          method: "post",
          data: this.$http.adornData({
            data: JSON.stringify(canvasdata),
            buildingId: this.currentbuildInfo.buildingId,
            customerId: this.$util.cookies.get("customer_id")
          })
        }).then((data) => {
          if (data && data.code === 0) {
            this.$message.success("保存成功!");
            //  this.$router.push({ path: '/tempctl-zutai'})
          } else {
            this.$message.error("操作失败!");
          }
        });
      },
		},
	}
</script>

<style>
  .objectTree1 {
    margin-left: 65px;
    position: absolute;
    overflow: auto;
    z-index: 100;
    height: 300px;
    /* border: 1px solid #ddd; */
    line-height: normal;
    z-index: 1204;
    box-shadow: 0px 0px 1px 1px #e2dfdf;
    margin-top: 327px;
    border-radius: 4px;
    background-color: white;
  }
  .w-1601{
    width: 535px
  }
</style>
